package com.linyx.simpleboot.zookeeper.LeaderElection;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.stereotype.Component;


//@Component
public class LeaderElectionTask {
	


	  private static final String PATH = "/LeaderElection";

	  private static int i;
	  
//	  @PostConstruct
	  public static void init() throws Exception {
		  schedule(i++);
		  
	  }

	  private static void schedule( int thread) throws Exception {
	    CuratorFramework client = getClient(thread);
	    CustomLeaderSelectorListenerAdapter leaderSelectorListener = new CustomLeaderSelectorListenerAdapter(client, PATH, "Client #" + thread);
	    leaderSelectorListener.start();
	  }

	  private static CuratorFramework getClient( int thread) {
	    RetryPolicy rp = new ExponentialBackoffRetry(1000, 3);
	    // Fluent风格创建
	    CuratorFramework client = CuratorFrameworkFactory.builder()
	        .connectString("127.0.0.1:2181")
	        .sessionTimeoutMs(1000000)
	        .connectionTimeoutMs(3000)
	        .retryPolicy(rp)
	        .build();
	    client.start();
	    System.out.println("Client [" + thread + "] Server connected...");
	    return client;
	  }

	

}
